package tag18_04_08.mvcAufgabe.swing;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import tag18_04_08.mvcAufgabe.Position;
import tag18_04_08.mvcAufgabe.TicTacToe;


public class ViewSwing extends JFrame implements ActionListener {

	private Cell[][] field;
	private TicTacToe game;

	public ViewSwing(TicTacToe game) {
		super("TicTacToe");
		
		this.game = game;
		
		int dim = game.getDim();
		
		setLayout(new GridLayout(dim, dim));
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setBounds(100, 100, 400, 400);
		
		field = new Cell[dim][dim];
		
		for (int row = 0; row < dim; row++) {
			for (int col = 0; col < dim; col++) {
				Cell cell = new Cell(row, col);
				cell.addActionListener(this);
				
				field[row][col] = cell;
				add(cell);
			}
		}
		
		setVisible(true);
	}
	
	public void setSign(Position position, int state) {
		Cell cell = field[position.getRow()][position.getCol()]; 
		cell.setSign(state);
		cell.removeActionListener(this);
	}
	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		Cell cell = (Cell)e.getSource();
		
		Position userPos = cell.getPosition();
		
		game.moveUser(userPos);
		cell.setSign(TicTacToe.USER);
		
		//Check is over
		if( game.isGameOver() ) {
			showResult();
			return;
		}
		
		//AI move
		Position aiPos = game.moveAi();
		setSign(aiPos, TicTacToe.AI);
		
		//Check is over
		if( game.isGameOver() ) {
			showResult();
			return;
		}
	}
	
	private void showResult() {
		if(game.isWinnerAi()) {
			MessageDialog.showMessage("Sie haben verloren :(");
		} else if(game.isWinnerUser()) {
			MessageDialog.showMessage("Sie haben gewonnen!");
		} else if(game.isGameOver()) {
			MessageDialog.showMessage("Unentschieden");
		} else {
			MessageDialog.showError("Internal error: game is not over. Why show result?");
		}
		
	}	
}
